

import React, { useState, useRef } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, KeyboardAvoidingView, Platform, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { FontAwesome6 } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import styles from './styles';

type LoginType = 'password' | 'sms';

interface LoginFormData {
  username: string;
  password: string;
  phone: string;
  smsCode: string;
}

interface MessageState {
  type: 'error' | 'success' | null;
  text: string;
}

const LoginScreen: React.FC = () => {
  const router = useRouter();
  
  // 登录类型状态
  const [loginType, setLoginType] = useState<LoginType>('password');
  
  // 表单数据状态
  const [formData, setFormData] = useState<LoginFormData>({
    username: '',
    password: '',
    phone: '',
    smsCode: '',
  });
  
  // UI状态
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [rememberPassword, setRememberPassword] = useState(false);
  const [autoLogin, setAutoLogin] = useState(false);
  const [smsCountdown, setSmsCountdown] = useState(0);
  const [message, setMessage] = useState<MessageState>({ type: null, text: '' });
  
  // 引用
  const smsTimerRef = useRef<number | null>(null);
  
  // 切换登录类型
  const handleSwitchLoginType = (type: LoginType) => {
    setLoginType(type);
    hideMessage();
  };
  
  // 切换密码可见性
  const handleTogglePasswordVisibility = () => {
    setIsPasswordVisible(!isPasswordVisible);
  };
  
  // 更新表单数据
  const updateFormData = (field: keyof LoginFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    hideMessage();
  };
  
  // 显示消息
  const showMessage = (type: 'error' | 'success', text: string) => {
    setMessage({ type, text });
    const timeout = type === 'error' ? 5000 : 3000;
    setTimeout(hideMessage, timeout);
  };
  
  // 隐藏消息
  const hideMessage = () => {
    setMessage({ type: null, text: '' });
  };
  
  // 手机号验证
  const validatePhone = (phone: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };
  
  // 获取验证码
  const handleGetSmsCode = () => {
    if (!formData.phone) {
      showMessage('error', '请先输入手机号');
      return;
    }
    
    if (!validatePhone(formData.phone)) {
      showMessage('error', '请输入正确的手机号');
      return;
    }
    
    // 开始倒计时
    startSmsCountdown();
    showMessage('success', '验证码已发送');
  };
  
  // 开始验证码倒计时
  const startSmsCountdown = () => {
    setSmsCountdown(60);
    
    if (smsTimerRef.current) {
      clearInterval(smsTimerRef.current);
    }
    
    smsTimerRef.current = setInterval(() => {
      setSmsCountdown(prev => {
        if (prev <= 1) {
          if (smsTimerRef.current) {
            clearInterval(smsTimerRef.current);
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };
  
  // 处理密码登录
  const handlePasswordLogin = async () => {
    if (!formData.username || !formData.password) {
      showMessage('error', '请填写完整的登录信息');
      return;
    }
    
    setIsLoading(true);
    hideMessage();
    
    try {
      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 登录成功，跳转到首页
      router.replace('/p-home');
    } catch (error) {
      showMessage('error', '登录失败，请检查用户名和密码');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理验证码登录
  const handleSmsLogin = async () => {
    if (!formData.phone || !formData.smsCode) {
      showMessage('error', '请填写完整的登录信息');
      return;
    }
    
    if (!validatePhone(formData.phone)) {
      showMessage('error', '请输入正确的手机号');
      return;
    }
    
    setIsLoading(true);
    hideMessage();
    
    try {
      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 登录成功，跳转到首页
      router.replace('/p-home');
    } catch (error) {
      showMessage('error', '登录失败，请检查验证码');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理登录
  const handleLogin = () => {
    if (isLoading) return;
    
    if (loginType === 'password') {
      handlePasswordLogin();
    } else {
      handleSmsLogin();
    }
  };
  
  // 忘记密码
  const handleForgotPassword = () => {
    showMessage('error', '请联系管理员重置密码');
  };
  
  // 清理定时器
  React.useEffect(() => {
    return () => {
      if (smsTimerRef.current) {
        clearInterval(smsTimerRef.current);
      }
    };
  }, []);
  
  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView
        style={styles.keyboardAvoidingView}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.scrollViewContent}
          keyboardShouldPersistTaps="handled"
        >
          {/* 顶部Logo区域 */}
          <LinearGradient
            colors={['#969FFF', '#5147FF', '#3E3987']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.logoHeader}
          >
            <View style={styles.logoContainer}>
              <View style={styles.appLogo}>
                <FontAwesome6 name="layer-group" size={32} color="#FFFFFF" />
              </View>
              <Text style={styles.appName}>流批通</Text>
              <Text style={styles.appSlogan}>高效移动审批平台</Text>
            </View>
          </LinearGradient>
          
          {/* 登录表单区域 */}
          <View style={styles.loginMain}>
            <View style={styles.loginCard}>
              {/* 登录方式切换 */}
              <View style={styles.loginTypeSwitch}>
                <TouchableOpacity
                  style={[
                    styles.switchTab,
                    loginType === 'password' && styles.switchTabActive
                  ]}
                  onPress={() => handleSwitchLoginType('password')}
                >
                  <Text style={[
                    styles.switchTabText,
                    loginType === 'password' && styles.switchTabTextActive
                  ]}>
                    账号密码登录
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={[
                    styles.switchTab,
                    loginType === 'sms' && styles.switchTabActive
                  ]}
                  onPress={() => handleSwitchLoginType('sms')}
                >
                  <Text style={[
                    styles.switchTabText,
                    loginType === 'sms' && styles.switchTabTextActive
                  ]}>
                    验证码登录
                  </Text>
                </TouchableOpacity>
              </View>
              
              {/* 账号密码登录表单 */}
              {loginType === 'password' && (
                <View style={styles.formContainer}>
                  <View style={styles.inputGroup}>
                    <Text style={styles.inputLabel}>用户名</Text>
                    <View style={styles.inputWrapper}>
                      <TextInput
                        style={styles.textInput}
                        placeholder="请输入用户名"
                        placeholderTextColor="#6B7280"
                        value={formData.username}
                        onChangeText={(value) => updateFormData('username', value)}
                        autoCapitalize="none"
                        autoCorrect={false}
                      />
                      <FontAwesome6 name="user" size={16} color="#6B7280" style={styles.inputIcon} />
                    </View>
                  </View>
                  
                  <View style={styles.inputGroup}>
                    <Text style={styles.inputLabel}>密码</Text>
                    <View style={styles.inputWrapper}>
                      <TextInput
                        style={styles.textInput}
                        placeholder="请输入密码"
                        placeholderTextColor="#6B7280"
                        value={formData.password}
                        onChangeText={(value) => updateFormData('password', value)}
                        secureTextEntry={!isPasswordVisible}
                        autoCapitalize="none"
                        autoCorrect={false}
                      />
                      <TouchableOpacity
                        style={styles.passwordToggleButton}
                        onPress={handleTogglePasswordVisibility}
                      >
                        <FontAwesome6
                          name={isPasswordVisible ? 'eye-slash' : 'eye'}
                          size={16}
                          color="#6B7280"
                        />
                      </TouchableOpacity>
                    </View>
                  </View>
                  
                  {/* 记住密码和自动登录 */}
                  <View style={styles.loginOptions}>
                    <TouchableOpacity
                      style={styles.checkboxContainer}
                      onPress={() => setRememberPassword(!rememberPassword)}
                    >
                      <View style={[styles.checkbox, rememberPassword && styles.checkboxChecked]}>
                        {rememberPassword && (
                          <FontAwesome6 name="check" size={12} color="#FFFFFF" />
                        )}
                      </View>
                      <Text style={styles.checkboxLabel}>记住密码</Text>
                    </TouchableOpacity>
                    
                    <TouchableOpacity
                      style={styles.checkboxContainer}
                      onPress={() => setAutoLogin(!autoLogin)}
                    >
                      <View style={[styles.checkbox, autoLogin && styles.checkboxChecked]}>
                        {autoLogin && (
                          <FontAwesome6 name="check" size={12} color="#FFFFFF" />
                        )}
                      </View>
                      <Text style={styles.checkboxLabel}>自动登录</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              )}
              
              {/* 验证码登录表单 */}
              {loginType === 'sms' && (
                <View style={styles.formContainer}>
                  <View style={styles.inputGroup}>
                    <Text style={styles.inputLabel}>手机号</Text>
                    <View style={styles.inputWrapper}>
                      <TextInput
                        style={styles.textInput}
                        placeholder="请输入手机号"
                        placeholderTextColor="#6B7280"
                        value={formData.phone}
                        onChangeText={(value) => updateFormData('phone', value)}
                        keyboardType="phone-pad"
                        maxLength={11}
                      />
                      <FontAwesome6 name="mobile-screen" size={16} color="#6B7280" style={styles.inputIcon} />
                    </View>
                  </View>
                  
                  <View style={styles.inputGroup}>
                    <Text style={styles.inputLabel}>验证码</Text>
                    <View style={styles.smsInputWrapper}>
                      <TextInput
                        style={styles.smsInput}
                        placeholder="请输入验证码"
                        placeholderTextColor="#6B7280"
                        value={formData.smsCode}
                        onChangeText={(value) => updateFormData('smsCode', value)}
                        keyboardType="number-pad"
                        maxLength={6}
                      />
                      <TouchableOpacity
                        style={[styles.getSmsCodeButton, smsCountdown > 0 && styles.getSmsCodeButtonDisabled]}
                        onPress={handleGetSmsCode}
                        disabled={smsCountdown > 0}
                      >
                        <Text style={styles.getSmsCodeButtonText}>
                          {smsCountdown > 0 ? `${smsCountdown}秒后重发` : '获取验证码'}
                        </Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              )}
              
              {/* 错误/成功提示 */}
              {message.type && (
                <View style={styles.messageContainer}>
                  <View style={[
                    styles.message,
                    message.type === 'error' ? styles.errorMessage : styles.successMessage
                  ]}>
                    <FontAwesome6
                      name={message.type === 'error' ? 'circle-exclamation' : 'circle-check'}
                      size={14}
                      color={message.type === 'error' ? '#B91C1C' : '#166534'}
                      style={styles.messageIcon}
                    />
                    <Text style={[
                      styles.messageText,
                      message.type === 'error' ? styles.errorMessageText : styles.successMessageText
                    ]}>
                      {message.text}
                    </Text>
                  </View>
                </View>
              )}
              
              {/* 登录按钮 */}
              <TouchableOpacity
                style={[styles.loginButton, isLoading && styles.loginButtonDisabled]}
                onPress={handleLogin}
                disabled={isLoading}
              >
                <LinearGradient
                  colors={['#969FFF', '#5147FF']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                  style={styles.loginButtonGradient}
                >
                  <Text style={styles.loginButtonText}>
                    {isLoading ? '登录中...' : '登录'}
                  </Text>
                  {isLoading && (
                    <FontAwesome6
                      name="spinner"
                      size={16}
                      color="#FFFFFF"
                      style={styles.loadingSpinner}
                    />
                  )}
                </LinearGradient>
              </TouchableOpacity>
              
              {/* 忘记密码 */}
              {loginType === 'password' && (
                <View style={styles.forgotPasswordContainer}>
                  <TouchableOpacity onPress={handleForgotPassword}>
                    <Text style={styles.forgotPasswordText}>忘记密码？</Text>
                  </TouchableOpacity>
                </View>
              )}
            </View>
          </View>
          
          {/* 底部版权信息 */}
          <View style={styles.footer}>
            <Text style={styles.copyrightText}>© 2024 流批通科技有限公司</Text>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default LoginScreen;

